package com.topisv.tms.web;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.topisv.tms.entity.Area;
import com.topisv.tms.entity.AreaGroup;
import com.topisv.tms.entity.Consignor;
import com.topisv.tms.entity.CustomerAreaGroup;
import com.topisv.tms.entity.Customers;
import com.topisv.tms.mybatis.SqlMapDao;
import com.topisv.tms.service.AreaGroupService;
import com.topisv.tms.service.AreaService;
import com.topisv.tms.service.CustomerAreaGroupService;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.utils.PubUtil;
import com.topisv.tms.web.base.BaseDataTableController;
import com.topisv.tms.web.dto.LeveDTO;
import com.topisv.tms.web.dto.WebAreaGroupDto;
import com.topisv.tms.web.dto.WebCustomersAreaGroupDto;

import net.sf.json.JSONObject;

@Controller
@RequestMapping(value = "/v2/customerAreaGroup")
public class CustomerAreaGroupController extends BaseDataTableController {
	
	private static final Logger log = LoggerFactory.getLogger(CustomerAreaGroupController.class);
	    
	@Autowired
	private CustomerAreaGroupService customerAreaGroupService;
	@Autowired
	private AreaGroupService areaGroupService;
	@Autowired
	private CustomersService customersService;
	@Autowired
	private AreaService areaService;
	@Autowired
	private SqlMapDao sqlMapDao;

	private String getAreaLists(String areaLists){
		if(areaLists==null){
			return areaLists;
		}
		StringBuffer sb=new StringBuffer();
		String[] lists=areaLists.split(",");
		for(String list:lists){
			Area area=areaService.findByAreaCode(list);
			if("".equals(sb.toString())){
				sb.append(area.getAreaName());
			}else{
				sb.append(","+area.getAreaName());
			}
		}
		return sb.toString();
	}

	@RequestMapping(value = "view/{id}")
	public String view(@PathVariable(value = "id") Long id,
			Model model) {
		Customers customers=customersService.findOne(id);
		List<AreaGroup> areaGroups = areaGroupService.loadByWarehouseType("paiu");
		List<AreaGroup> ts =areaGroupService.loadByCustomerCode(customers.getCustomerCode());
		List<AreaGroup> ags =new ArrayList<AreaGroup>();
		if(ts!=null&&(!ts.isEmpty())){
			areaGroups.addAll(ts);
			ags.addAll(ts);
		}
		WebCustomersAreaGroupDto webCustomersAreaGroupDto=new WebCustomersAreaGroupDto();
		List<WebAreaGroupDto> webAreaGroupDtos=new ArrayList<WebAreaGroupDto>();
		webCustomersAreaGroupDto.setCustomerCode(customers.getCustomerCode());
		webCustomersAreaGroupDto.setCustomerId(id);
		webCustomersAreaGroupDto.setCustomerName(customers.getCustomerName());
		webCustomersAreaGroupDto.setWebAreaGroupDtos(webAreaGroupDtos);
		for(AreaGroup areaGroup:areaGroups){
			WebAreaGroupDto webAreaGroupDto=new WebAreaGroupDto();
			webAreaGroupDto.setGroupCode(areaGroup.getGroupCode());
			webAreaGroupDto.setGroupIntro(areaGroup.getGroupIntro());
			webAreaGroupDto.setId(areaGroup.getId());
			webAreaGroupDto.setGroupName(areaGroup.getGroupName());
			CustomerAreaGroup customersAreagroup=customerAreaGroupService.findByCustomerCodeAndAreaGroupCode(customers.getCustomerCode(), areaGroup.getGroupCode());
			if(customersAreagroup!=null){
				String areaLists=customersAreagroup.getAreaLists();
				areaLists=(null==areaLists||"null".equals(areaLists))? "":getAreaLists(areaLists);
				webAreaGroupDto.setAreas(areaLists);
				webAreaGroupDto.setNextGroupCode(customersAreagroup.getGroupCodes());
				webAreaGroupDto.setLevel(customersAreagroup.getLevel());
				ags.add(areaGroup);
			}
			webAreaGroupDtos.add(webAreaGroupDto);
		}
		List<Area> provinces = areaService.findProvoce();
		model.addAttribute("provinces", provinces);
		model.addAttribute("customers", customers);
		model.addAttribute("object", webCustomersAreaGroupDto);
		model.addAttribute("ags", ags);
		return "customers/customersAreaGroups";
	}
	
	@RequestMapping(value = "ajaxSynCustomerAreaGroup")
	public void ajaxSynCustomerAreaGroup(
			@RequestParam(value = "customerCode") String customerCode,
			HttpServletResponse response) {
		JSONObject json = null;
		PrintWriter out = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			customerAreaGroupService.setCustomerAreaGroup(customerCode);
			json.put("status", "1");
			json.put("content", "同步成功");
			out.print(json.toString());
		} catch (Exception e) {
			
			log.error("取消订单接口异常", e);
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
		}
	}
	
	@RequestMapping(value = "ajaxSetGroupCodes")
	public void ajaxSetGroupCodes(
			@RequestParam(value = "customerCode") String customerCode,
			@RequestParam(value = "groupCode") String groupCode,
			@RequestParam(value = "params") String params,
			HttpServletResponse response) {
		JSONObject json = null;
		PrintWriter out = null;
		try {

			log.info("开始配置订单库存流转网点数据");
			json = new JSONObject();
			out = response.getWriter();
			CustomerAreaGroup ca=customerAreaGroupService.findByCustomerCodeAndAreaGroupCode(customerCode, groupCode);
			if(ca==null){
				json.put("status", "0");
				json.put("content", "数据有误");
			}else{
				ca.setGroupCodes(params);
				this.customerAreaGroupService.save(ca);
				json.put("status", "1");
				json.put("content", "同步成功");
				log.info("起始网点:"+ca.getAreaGroupCode());
				log.info("配置的参数:"+params);
			}
			
			out.print(json.toString());
		} catch (Exception e1) {
			
			json.put("status", "0");
			json.put("content", e1.getMessage());
			out.print(json.toString());
		}
		log.info(json.toString());
	}
	
	@RequestMapping(value = "ajaxCustomerAreaGroup")
	public void ajaxCustomerAreaGroup(
			@RequestParam(value = "customerCode") String customerCode,
			@RequestParam(value = "groupCode") String groupCode,
			HttpServletResponse response) {
		JSONObject json = null;
		PrintWriter out = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			List<LeveDTO> ls=new ArrayList<LeveDTO>();

			Map<String, LeveDTO> maps=new HashMap<String, LeveDTO>();
			CustomerAreaGroup ca=customerAreaGroupService.findByCustomerCodeAndAreaGroupCode(customerCode, groupCode);
			if(ca==null){
				json.put("status", "0");
				json.put("content", "数据有误");
				out.print(json.toString());
				return;
			}
			String codes=ca.getGroupCodes();
			List<CustomerAreaGroup> csags=this.customerAreaGroupService.findByCustomerCode(customerCode);
			List<AreaGroup> areaGroups=this.areaGroupService.loadByCustomerCode(customerCode);
			for(AreaGroup a:areaGroups){
				LeveDTO l=new LeveDTO();
				l.setGroupCode(a.getGroupCode());
				l.setGroupName(a.getGroupName());
				ls.add(l);
				maps.put(a.getGroupCode(), l);
			}
			if(csags!=null){
				for(CustomerAreaGroup c:csags){
					if(groupCode.equals(c.getAreaGroupCode())){
						continue;
					}
					LeveDTO l=new LeveDTO();
					AreaGroup a=this.areaGroupService.findByGroupCode(c.getAreaGroupCode());
					l.setGroupCode(c.getAreaGroupCode());
					l.setGroupName(a.getGroupName());
					ls.add(l);
					maps.put(a.getGroupCode(), l);
				}
			}
			if(codes!=null){
				String[] lists=codes.split(",");
				for(String list:lists){
					String[] values=list.split(":");
					LeveDTO leveDTO=maps.get(values[0]);
					if(leveDTO!=null){
						leveDTO.setLeve(values[1]);
					}
				}
			}
			
			ca.setLeveDTOs(ls);
			json.put("status", "1");
			json.put("content", ca);
			
			
		} catch (Exception e1) {
			
			json.put("status", "0");
			json.put("content", e1.getMessage());
		}
		out.print(json.toString());
		log.info(json.toString());
	}
	
	/**
	 * 跳转到新增绑定仓库页面
	 */
	@RequestMapping(value = "createBindWarehouse/{customerCode}",method = RequestMethod.GET)
	public String createBindWarehouse(@PathVariable(value="customerCode") String customerCode,Model model) {
		ShiroUser curUser = getShiroUser();
		List<AreaGroup> warehouseList=null;
		warehouseList = areaGroupService.loadAreaGroupByAuthority(curUser, customerCode);
		model.addAttribute("warehouseList", warehouseList);
		model.addAttribute("customerCode", customerCode);
		return "customers/customerWarehouseList";

	}
	
	@RequestMapping(value = "queryCustomerWarehouseList",method = RequestMethod.POST)
	public void queryCustomerWarehouseList(ServletRequest request,HttpServletResponse response) {
			JSONObject json = null;
			PrintWriter out = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			String msg="";
			String customerCode=request.getParameter("customerCode");
			json.put("status","success");
			List<CustomerAreaGroup> list=customerAreaGroupService.findByCustomerCode(customerCode);
			if (list != null && !list.isEmpty()) {
				setDetail(list);
			}
			json.put("content",list);
		} catch (Exception e) {
			log.error("error",e);
			json.put("status","error");
			json.put("content",e.getMessage());
		}
		out.print(json.toString());
	}
	private void setDetail(List<CustomerAreaGroup> list){
		for(CustomerAreaGroup group:list){
			group.setAreaGroupName(areaGroupService.findByGroupCode(group.getAreaGroupCode()).getGroupName());
		}
	}
	
	@RequestMapping(value = "updateCustomerWarehouseCainiaoAddress",method = RequestMethod.POST)
	public void updateCustomerWarehouseCainiaoAddress(ServletRequest request,HttpServletResponse response) {
			JSONObject json = null;
			PrintWriter out = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			Long id=Long.parseLong(request.getParameter("id"));
			String useWarehouseAddress=request.getParameter("useWarehouseAddress");
			CustomerAreaGroup customerAreaGroup=customerAreaGroupService.findOne(id);
			/**begin add 20160722 如果没有配置发货人信息，就不能修改状态*/
			if ("1".equals(useWarehouseAddress)) {
				List<Consignor> consignorList = PubUtil.convertListMapToObject(sqlMapDao
						.selectList("consignorMapper.getConsignorByCustomerCode", customerAreaGroup),Consignor.class);
				if (consignorList == null || consignorList.isEmpty()) {
					json.put("status","error");
					json.put("content","您尚未配置发货人信息及地址，请在 【发货人管理】中进行配置");
					out.print(json.toString());
					return;
				}
			}
			/**end add 20160722 如果没有配置发货人信息，就不能修改状态*/
			customerAreaGroup.setCainiaoAddressStatus(useWarehouseAddress);
			customerAreaGroupService.save(customerAreaGroup);
			json.put("status","success");
			json.put("content","成功");
		} catch (Exception e) {
			log.error("error",e);
			json.put("status","error");
			json.put("content",e.getMessage());
		}
		out.print(json.toString());
	}
	@RequestMapping(value = "updateCustomerAreaGroup",method = RequestMethod.POST)
	public void updateCustomerAreaGroup(ServletRequest request,HttpServletResponse response) {
			JSONObject json = null;
			PrintWriter out = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			Long id=Long.parseLong(request.getParameter("id"));
			CustomerAreaGroup customerAreaGroup=customerAreaGroupService.findOne(id);
			customerAreaGroup.setAreaGroupName(
					areaGroupService.findByGroupCode(customerAreaGroup.getAreaGroupCode()).getGroupName());
			json.put("status","success");
			json.put("content",customerAreaGroup);
		} catch (Exception e) {
			log.error("error",e);
			json.put("status","error");
			json.put("content","删除失败");
		}
		out.print(json.toString());
	}
}
